// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App';
import router from './router';
import axios from 'axios';
import "babel-polyfill";
import util from './common/public.js';
import Router from 'vue-router';
import VueHighcharts from "vue2-highcharts";
import store from '../vuex/index';

Vue.use(ElementUI);
Vue.use(Router);

Vue.component("VueHighcharts", VueHighcharts);

Vue.config.productionTip = false;
Vue.prototype.$axios = axios;
Vue.prototype.$util = util;

// axios.defaults.baseURL = util.domain;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // config.headers.Authorization = {};
    config.baseURL = config.url.indexOf("/node/") > -1 ? util.domain_node : util.domain;

    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    if (error.response) {
        switch (error.response.status) {
            case 401:
                store.dispatch('SIGNOUT');
                util.errorMsg("登录失效，请重新登录");
                router.replace({
                    path: 'login'
                })
        }
    }

    return Promise.reject(error);
});

//路由跳转前验证是否登录，如果没有则重定向到登录页
router.beforeEach(({ path }, from, next) => {
    let isLogin = Boolean(store.state.user.userName);

    if (!isLogin && path !== '/login') {
        return next({ path: '/login' })
    }
    next();
})
// Loading chunk {n} failed问题的解决方法
router.onError((error) => {
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    const targetPath = router.history.pending.fullPath;
    if (isChunkLoadFailed) {
        router.replace(targetPath);
    }
});

/* eslint-disable no-new */
new Vue({
    el: '#app',
    store,
    router,
    components: { App },
    template: '<App/>'
})
